const fs = require('fs');
const util = require('util')
const readFile = util.promisify(fs.readFile)
const path = require('path')
const webpack = require('webpack')
const {
  RawSource
} = webpack.sources
class Plugin2 {

  apply(compiler) {
    // 初始化compilation钩子
    compiler.hooks.thisCompilation.tap('Plugin2', (compilation) => {
      // 添加资源
      compilation.hooks.additionalAssets.tapAsync('Plugin2', async (cb) => {
        // debugger
        // console.log(compilation)
        // 1.静态添加
        // 输出的资源添加 a.txt
        const content = 'my Plugin txt'
        compilation.assets['a.txt'] = {
          // 文件大小
          size() {
            return content.length
          },
          // 文件内容
          source() {
            return content
          },
        }
        // 2.动态添加
        const data = await readFile(path.resolve(__dirname, 'b.txt'))
        // compilation.assets['b.txt'] = new RawSource(data)
        // 3 emitAsset
        compilation.emitAsset('b.txt',new RawSource(data))
        cb()
      })
    })
  }

}

module.exports = Plugin2;